'use strict'

let Trade = require('./model').Trade
let Ids = require('./model').Ids
let serverConfig = require('../../config/serverConfig').serverConfig
let serverId = serverConfig.serverId

/**
 * 新建角色并保存
 */
exports.newAndSave = function(t, callback) {
    Ids.findAndModify({
        _id: serverId
    }, [], {
        $inc: {
            tradeId: 1
        }
    }, {}, function(err, res) {
        if (err || !res.value) throw err;
        let id = res.value.tradeId * 1000 + serverId//id后面3位是服务器id

        let trade = new Trade({
            _id: id,
            pId: t.playerId,
            pName: t.pName,
            itemId: t.itemId || 0, //物品id
            itemNum: t.itemNum || 0, //数量
            sellTime: new Date().getTime(), //出售时间
            sellGold: t.sellGold || 1, //出售单价
            sellType: t.sellType, //物品类型
        })

        trade.save(callback)
    });
}

/**
 * 根据查询条件, 查找物品
 */
exports.getItemByQuery = function(query, callback) {
    Trade.findOne(query, function(err, res) {
        callback(err, res)
    })
}

/**
 * 根据查询条件, 查找物品
 */
exports.getItemsByQuerys = function(query, page, limit, callback) {
    Trade.find(query)
        .skip(page * limit)
        .limit(limit + 1)
        .sort('sellGold -sellTime')
        .select('pName itemId itemNum sellGold')
        .exec(callback);
}

/**
 * 根据查询条件, 查找物品
 */
exports.getItemsByQuery = function(query, callback) {
    Trade.find(query, function(err, res) {
        callback(err, res)
    })
}

/**
 * 根据查询条件, 删除物品
 */
exports.removeItemByQuery = function(query, callback) {
    Trade.remove(query, callback)
}


exports.itemCount = function(pId, callback){
  Trade.count({
    pId:pId
  }, callback)
}
